<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/15
 * Time: 11:13 AM
 */
namespace app\backend\controllers;

use app\common\helpers\AdminSession;
use app\common\helpers\Utils;
use app\common\models\AdminLog;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use app\common\models\AdminUser;
use app\common\helpers\Url;
use app\common\helpers\Cache;
use Illuminate\Support\Facades\DB;
use app\backend\controllers\BaseController;
use app\common\facades\Setting;

class LoginController extends BaseController
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin';
    protected $username;


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(){
        //     $this->middleware('guest:admin', ['except' => 'logout']);
    }

    /**
     * 自定义字段名
     * 可使用
     * @return array
     */
    public function atributeNames(){
        return [
            'username' => '用户名',
            'password' => '密码',
            'captcha' => '验证码'
        ];
    }

    /**
     * 字段规则
     * @return array
     */
    public function rules(){
        return [
            'username' => 'required',
            'password' => 'required',
            'captcha' => 'required|captcha'
        ];
    }

    /**
     * 自定义认证驱动
     * @return [type]                   [description]
     */
    protected function guard(){
        return auth()->guard('admin');
    }

    /**
     * 重写验证字段.
     *
     * @return string
     */
    public function username(){
        return 'username';
    }

    public function index(){
        return view("backend.login.index");
    }
    /**
     * Log the user out of the application.
     *
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(){
        $this->guard('admin')->logout();
        request()->session()->flush();
        request()->session()->regenerate();

        AdminSession::flush();

        return $this->successJson('成功', []);
    }

    /**
     * 登录
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function login(Request $request){
        $request->offsetSet('password',$request->password);
        try {
            $this->validate($this->rules(), $request, [], $this->atributeNames());
        } catch (\Exception $e) {
            return $this->errorJson($e->getMessage());
        }
        /*if (!$request->captcha || app('captcha')->platformCheck($request->captcha) == false)
        {
            return $this->errorJson('图形验证码错误');
        }*/

        if ($this->attemptLogin($request,false)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * 重写登录成功json返回
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendLoginResponse(Request $request){
        $request->session()->regenerate();
        $loginToken = rand(1000, 9999).time();
        session(['login_token'=>$loginToken]);
        $this->clearLoginAttempts($request);

        $model = AdminUser::where('uid', $this->guard()->user()->uid);
        $model->update([
            'lastvisit' =>  time(),
            'lastip' => Utils::getClientIp(),
            'login_token' => $loginToken
        ]);
        $adminUser = $model->first();
        $this->addLogsAction($this->guard()->user()->uid,$adminUser['username'],'超级管理员');
        AdminSession::setAdminUserId($adminUser['uid']);
        return $this->successJson('成功');
    }

    /**
     * 重写登录失败json返回
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request){
        return $this->errorJson(Lang::get('auth.failed'), []);
    }

    /**
     * 重写登录失败次数限制
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendLockoutResponse(Request $request){
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );

        $message = Lang::get('auth.throttle', ['seconds' => $seconds]);

        return $this->errorJson($message);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request,$rememberPwd = ''){
//        if($rememberPwd == 1)
//        {
//            $remember = 1;
//        }else{
//            $remember = $request->remember;
//        }
        $remember = 1;
        return $this->guard()->attempt(
            $this->credentials($request),$remember
        );
    }

    public function getInfo(){
        $default = [
            'site_name' => "芸签内容管理系统",
            'site_logo' => fmt_media_url("/static/images/site_logo.png"),
            'title_icon' => fmt_media_url("/static/images/title_icon.png"),
            'advertisement' => fmt_media_url("/static/images/nopic.jpg"),
            'information' => ''
        ];
        $siteSetting = Setting::get('cms.site');
        $siteInfo = [];

        $siteInfo['site_name'] = $siteSetting['site_name'] ? $siteSetting['site_name'] : $default['site_name'];
        $siteInfo['site_logo'] = $siteSetting['site_logo'] ? $siteSetting['site_logo'] : $default['site_logo'];
        $siteInfo['title_icon'] = $siteSetting['title_icon'] ? $siteSetting['title_icon'] : $default['title_icon'];
        $siteInfo['advertisement'] = $siteSetting['advertisement'] ? $siteSetting['advertisement'] : $default['advertisement'];
        $siteInfo['information'] = $siteSetting['information'] ? $siteSetting['information'] : $default['information'];

        $siteInfo['captcha']['status'] = true;
        $captcha = app('captcha');
        $captchaBase64 = $captcha->create('default', true,true);
        $siteInfo['captcha']['img'] = $captchaBase64['img'];

        if ($siteInfo) {
            return $this->successJson('成功', $siteInfo);
        } else {
            return $this->errorJson('没有检测到数据', '');
        }
    }


    //添加登录记录
    protected function addLogsAction($userId,$username, $detail_remark){
        $detail_parameter = array($detail_remark, 0);
        list($remark, $uniacid) = $detail_parameter;//依次：其他管理员类型，默认会员ID，默认类型
        //添加登录记录
        $model = new AdminLog();
        $model->site_id = \YunCms::siteId();
        $model->admin_uid = $userId?:0;
        $model->remark = $remark;
        $model->ip = Utils::getClientIp() ?: '';
        $model->username = $username;
        $model->save();
    }
    public function refreshCaptcha()
    {
        $captcha = app('captcha');
        $captcha_base64 = $captcha->create('default', true,true);
        return $this->successJson('成功', $captcha_base64['img']);
    }
}